<?php

namespace app\common\model;

use think\Model;
use think\Db;
use app\common\model\User;

/**
 * 交易 买入 卖出
 */
class UserTrade extends Model
{
	public function buyer()
	{
		return $this->hasOne('User','uid', 'buyer_uid')
			->field('uid,name,tel,bank,banknum,wechat,alipay');
	}

	public function seller()
	{
		return $this->belongsTo('User','seller_uid', 'uid')
			->field('uid,name,tel,bank,banknum,wechat,alipay');
	}

	/**
	 * 	大厅交易记录
	 * 
	 * @param  [type] $map   条件
	 * @param  [type] $size  每页数目
	 * @param [type] $field  查询字段值
	 * @return [type]       [description]
	 */
	public function getList($map = [], $size = null, $field = '*')
	{
		$list = $this->with('seller,buyer')->where($map)->field($field)->paginate($size);
		return $list;
	}

	/**
	 * 单条交易记录信息
	 *
	 * @param [int] $id	主键id值
	 * @return void
	 */
	public function getInfo($id)
	{
		$info = $this->with('buyer,seller')->where('id', $id)->find();
		return $info;
	}

   	/**
   	 * 玩家卖出，添加交易记录
   	 * 
   	 * @param [type] $data [description]
   	 * @param [type] $uid  玩家id
   	 */
    public function addInfo($data, $uid)
    {
		if ($data['num'] <= 0) {
			return msg_code('请输入合法数字');
		}
		if ($data['num'] < config('sell_base') || $data['num'] % config('sell_base') > 0) {
			return msg_code('卖出金额需为'.config('sell_base').'整数倍');
    	}

    	$user = new User();
    	$info = $user->where('uid', $uid)->field('s_pwd,kr_coin,tg_coin,hg_coin,sc_coin')->find();

    	if ($info['s_pwd'] != encrypt($data['s_pwd'])) {
			return msg_code('支付密码不正确');
    	}

    	$coin = config('coin');
    	$acc_type = $coin[$data['from']];

    	if ($data['num'] > $info[$acc_type]) {
			return msg_code('账户余额不足');
		}
		
    	$addData = [ 
			'trade_no' => time().rand(123,987),
    		'seller_uid' => $uid,
			'trade_num' => $data['num'],
			'fee' => $data['num'] * config('sell_fee') / 100,
    	];

    	Db::startTrans();
    	try {
    		$this->save($addData);
    		$user->updateUserAcc($uid, -$data['num'], $acc_type, '交易卖出');
			Db::commit();
			return msg_code('卖出成功', 1);
    	} catch (Exception $e) {
			Db::rollback();
			return msg_code($e->getMessage());
    	}
    }

    /**
     * 	确认交易完成
     * 
     * @param  [type] $data 变更数据
     * @param  [type] $id   交易id号
     * @return [type]       [description]
     */
    public function confirm($data)
    {
		$info = $this->where('id', $data['id'])->find();
		if ($info['status'] == 1) {
			if ($data['pwd'] != encrypt($data['s_pwd'])) {
				return msg_code('支付密码不正确');
			}

			Db::startTrans();
			try {
				model('User')->updateUserAcc(
					$info['buyer_uid'], 
					$info['trade_num'], 
					'tg_coin', '交易单号：'.$info['trade_no'].'买入成功'
				);

				$this->where('id',$info['id'])->setField('status', 2);
				Db::commit();
				return msg_code('操作成功', 1);
			} catch (Exception $e) {
				Db::rollback();
				return msg_code($e->getMessage());
			}
		}
		return msg_code('请重新确认交易信息！');
	}	
	
	/**
	 * 玩家买入，添加玩家信息
	 *
	 * @param [type] $data
	 * @return void
	 */
	public function addBuyer($data)
	{
		// 锁定订单状态，等待买家打款
		$info = $this->where('id', $data['id'])->find();
		
		if (isset($data['buyer_uid'])) {

			$buyerInfo = db('user')->where('uid', $data['buyer_uid'])->field('is_agent,s_pwd')->find();

			if (! $buyerInfo['is_agent']) {
				return msg_code('只有代理身份才可执行买入');
			}
			if ($data['buyer_uid'] == $info['seller_uid']) {
				return msg_code('不支持自卖自买！');
			}
			if ($info['buyer_uid'] && $data['buyer_uid'] != $info['buyer_uid']) {
				return msg_code('此单已有买家执行买入！');
			}


			// if ($buyerInfo['s_pwd'] != encrypt($data['s_pwd'])) {
			// 	return msg_code('支付密码不正确！');
			// }
		}

		if (isset($data['voucher'])) {
			$data['voucher'] = base64_imgup($data['voucher'], 'voucher');
		}
		// 添加买家，锁定状态
		$data['status'] = 1;
		$data['update_time'] = date('Y-m-d H:i:s');
		$rst = $this->where('id', $data['id'])->update($data);
		return msg_code('操作完成！', $rst);
	}

	/**
     * 由系统确认收款
     * 
     * @param  [type] $id   [description]
     * @param  string $note [description]
     * @return [type]       [description]
     */
    public function sysConfirm($id, $note = '系统')
    {
        $info = $this->where('id', $id)->find();

        if ($info) {
            if ($info['status'] == 1) {
                Db::startTrans();
                try {
                    $this->where('id', $id)->update(['status' => 2, 'note' => $note.'确认收款']);
                    model('User')->updateUserAcc(
                        $info['buyer_uid'], 
                        $info['trade_num'], 
                        'kr_coin', 
                        '交易单号：'.$info['trade_no'].'#由'.$note.'确认收款'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }

            return msg_code('此交易状态异常');
        }   

        return msg_code('不存在此交易记录');
    }

    /**
     * 驳回玩家挂卖申请
     * 
     * @param  [type] $id   [description]
     * @param  string $note [description]
     * @return [type]       [description]
     */
    public function reject($id, $note = '', $uid = 0)
    {
       	$info = $this->where('id', $id)->find();
        if ($info) {
        	if ($uid) {
	       		if ($info['seller_uid'] != $uid) {
	       			return msg_code('暂无权限');
	       		}
	       	}
        	
            if ($info['status'] == 0) {
                Db::startTrans();
                try {
                    $this->where('id', $id)->update(['status' => -1, 'note' => $note.'取消挂卖请求']);
                    model('User')->updateUserAcc(
                        $info['seller_uid'], 
                        $info['trade_num'], 
                        'tg_coin', 
                        $note.'取消挂卖请求'
                    );
                    Db::commit();
                    return msg_code('操作成功！', 1);
                } catch (Exception $e) {
                    return msg_code($e->getMessage());
                }
            }

            return msg_code('此交易状态异常');
        }   

        return msg_code('不存在此交易记录'); 
    }
}
